package com.liu.user.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.liu.common.controller.CommonController;
import com.liu.common.entity.R;
import com.liu.common.entity.enums.PermissionEnum;
import com.liu.user.entity.base.UserBasicsInfo;
import com.liu.user.entity.dto.UserLoginInfoVO;
import com.liu.user.entity.qo.UserLoginQO;
import com.liu.user.service.IUserBasicsInfoService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 用户基础信息表 前端控制器
 * </p>
 *
 * @author LiuChengLong
 * @since 2022-09-07
 */
@RestController
@RequestMapping("/user/userBasicsInfo")
public class UserBasicsInfoController extends CommonController {

    @Resource
    private IUserBasicsInfoService userBasicsInfoService;

    /**
     * 用户注册
     * @param userBasicsInfo 用户注册信息
     * @return R
     */
    @PostMapping("/register")
    public R<String> register(@RequestBody UserBasicsInfo userBasicsInfo){
        try {
            userBasicsInfoService.register(userBasicsInfo);
            return R.success();
        } catch (Exception e) {
            return R.failed();
        }
    }

    /**
     * 用户登录
     * @param userLoginQO 用户登录信息
     * @return R
     */
    @PostMapping("/login")
    public R<UserLoginInfoVO> login(@RequestBody UserLoginQO userLoginQO){
        UserLoginInfoVO user = userBasicsInfoService.login(userLoginQO);
        if (user != null){
            return R.success(user);
        }else {
            return R.failed();
        }
    }

    /**
     * 更新用户信息
     * @param userBasicsInfo 用户更新信息
     * @return R
     */
    @PostMapping("/update")
    public R<T> update(@RequestBody UserBasicsInfo userBasicsInfo){
        // 验证用户是否有更新用户信息权限
        boolean hasPermission = StpUtil.hasPermissionOr(PermissionEnum.UPDATE_USER_INFO.getCode(), PermissionEnum.IS_ADMIN.getCode());
        if (hasPermission){
            userBasicsInfo.setUpdateBy(this.getUserId());
            userBasicsInfoService.updateById(userBasicsInfo);
            return R.success();
        }else {
            return R.failed();
        }
    }

    /**
     * 获取自身信息
     * @return R
     */
    @GetMapping("/getOneselfInfo")
    public R<UserBasicsInfo> getOneselfInfo(){
        Integer userId = this.getUserId();
        if (userId != null) {
            UserBasicsInfo userBasicsInfo = userBasicsInfoService.getById(userId);
            return R.success(userBasicsInfo);
        } else {
            return R.failed();
        }
    }

}

